// packageA/pages/consumableEdit/consumableEdit.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //修改信息回显
    editInfo:{},
    editInfoOld:{},
    //提交按钮禁用
    disabled:false,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //赠送耗材记录
    freeConsumables: [],
    //折叠面板
    activeFree: null,
    //无数据
    showNothing: false
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getUserProfile({
      desc: '为您提供更好的服务',
      success: (res) => {}
    })

    if(options.paramObj){
      this.setData({
        paramObj: JSON.parse(options.paramObj)
      })

      console.log('耗材接待传参');
      console.log(JSON.parse(options.paramObj));

      //获取修改数据
      this.getInfo();
    }  
  },    

  //提交表单
  confirmForm(e){
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let info=td.editInfo;  

    //非空验证
    if(!info.receiverWay){
      Toast.fail('请选择接待方式');
      return;
    }

    let receiveResult=obj.receiveResult.trim();
    if(!this.formNotEmpty(receiveResult,'receiveResultMessage','请输入处理结果')){
      return;
    }

    let param={
      className:'afterSaleConsumableOrder',
      data:{
        id: td.paramObj.id,
        //接待方式
        receiverWay: info.receiverWay,
        //处理结果
        receiveResult: receiveResult,
        //是否生成出库单
        createdOutOrder: false
      }
    }

    //console.log(param.data);

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });  

    CommonService.goSave(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');

        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
    })
  },

  //获取修改数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'afterSaleConsumableOrder',
      data: {
        id:this.data.paramObj.id,
        selectFields: ['id','receiver','receiverDate','receiverWay','receiveResult','consumableGiftNumber']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let info=res.data.data.result[0];  

        console.log('耗材接待回显');
        console.log(info);

        this.setData({
          editInfo: info
        }) 
      }
    }).catch((error) => {
    })
  },  

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },
  
  
  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.target.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //故障类型
    if(field=='receiverWay'){
      this.setData({
        selectTitle: '接待方式',
        showSelectSearch: false
      })
      this.getTypeList();
    }  
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //故障类型
    if(selectField=='receiverWay'){
      obj='editInfo.receiverWay';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //查询接待方式
  getTypeList(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'consumableOrderType',
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id:item.id,
              name:item.name
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  }, 

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //获取耗材赠送历史记录
  onGetFreeConsumables(){
    this.setData({
      showNothing: false
    })

    let param = {
      id: this.data.paramObj.id,
      equipmentNo: this.data.paramObj.equipmentNo
    }

    CommonService.freeConsumables(param).then(res=>{
      if(res.data.data && res.data.data.data && res.data.data.data.length){
        let result = res.data.data.data;
        console.log('耗材赠送历史记录');
        console.log(result);

        //如果只有一条则展开折叠面板
        if(result.length==1){
          this.setData({
            activeFree: result[0].current
          })
        }

        this.setData({
          freeConsumables: result
        }) 
      }else{
        this.setData({
          showNothing: true
        }) 
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //切换折叠面板
  onChangeFree(event) {
    this.setData({
      activeFree: event.detail
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})